package com.woniuxy.portal.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniuxy.portal.common.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.timeout}")
    private int timeout;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 访问资源之前执行校验，登录后才能访问受限资源
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头
        String token = request.getHeader("Authorization");
        System.out.println("request.getRequestURI() + token:  " +request.getRequestURI()+"  " + token);
        if (!StringUtils.hasText(token)) {
            // token为空，说明没有登录
            log.error("拦截器校验失败，token为空:" + request.getRequestURI());
            response.sendRedirect("/login.html");
            return false;
        }
        //2. 处理请求头，请求头格式： "Bearer xxqqee"
        token = token.replace("Bearer ","");
        //3. 校验token
        boolean verify = JWTUtil.verify(token, secret.getBytes());
        if (!verify) {
            log.error("拦截器token校验失败！" + request.getRequestURI());
            response.sendRedirect("/login.html");
            return false;
        }
        //4. 解析token
        JWT jwt = JWTUtil.parseToken(token);
        Object userId = jwt.getPayload("userId");
        //5. 判断token是否失效：如果在redis不存在说明token失效。 或者token错误。
        String redisKey = RedisConstant.USER_TOKEN_PREFIX + userId;
        if (!redisTemplate.hasKey(redisKey)) {
            log.error("拦截器token校验失败，token已过期！" + request.getRequestURI());
            response.sendRedirect("/login.html");
            return false;
        }
        //6. token续期
        redisTemplate.expire(redisKey,timeout, TimeUnit.MINUTES);
        // 所有的校验都通过：token非空、解析成功、在redis中也存在、完成了续期;
        // 说明校验成功，放行
        return true;
    }
}
